package com.nowcoder.community.event;/**
 * 功能描述
 *
 * @author 21775
 * @date 2022/09/24  20:47
 */

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.ElasticSearchService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.utils.CommunityConstUtil;
import com.nowcoder.community.utils.CommunityUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 *@ClassName ConsumerEvent
 *@Description TODO 消费者事件
 *@Author 21775
 *@Date 2022/9/24 20:47
 *@Version 1.0
 */
@Component
@Slf4j
public class ConsumerEvent implements CommunityConstUtil {
    @Resource
    private MessageService messageService;

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private ElasticSearchService elasticSearchService;

    @Resource
    private ThreadPoolTaskScheduler taskScheduler;

    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Value("${qiniu.bucket.header.name}")
    private String headerBucketName;

    @Value("${qiniu.bucket.header.url}")
    private String headerBucketUrl;

    @Value("${qiniu.bucket.share.name}")
    private String shareBucketName;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @KafkaListener(topics = {TOPIC_COMMENT,TOPIC_FOLLOW,TOPIC_LIKE})
    public void handleCommentMessage(ConsumerRecord<String,Object> record){
        if (record == null || record.value() == null) {
            log.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误!");
            return;
        }

        //发送站内通知
        Message message=new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());
        Map<String,Object> map=new HashMap<>();
        map.put("userId",event.getUserId());
        map.put("entityType",event.getEntityType());
        map.put("entityId",event.getEntityId());
        if(!event.getData().isEmpty()){
            for(Map.Entry<String,Object> entry:event.getData().entrySet()){
                map.put(entry.getKey(),entry.getValue());
            }
        }
        message.setContent(JSONObject.toJSONString(map));
        messageService.addMessage(message);
    }

    // 消费发帖事件
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误!");
            return;
        }

        DiscussPost post = discussPostService.findDiscussPostById(event.getEntityId());
        elasticSearchService.saveDiscussPost(post);
    }


    // 消费删帖事件
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误!");
            return;
        }

        elasticSearchService.deleteDiscussPost(event.getEntityId());
    }

    //消费分享事件
    @KafkaListener(topics = TOPIC_SHARE)
    public void handleShareMessage(ConsumerRecord record) {
        if (record == null || record.value() == null) {
            log.error("消息的内容为空!");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误!");
            return;
        }

        String htmlUrl = (String) event.getData().get("htmlUrl");
        String fileName = (String) event.getData().get("fileName");
        String suffix = (String) event.getData().get("suffix");

        String cmd = wkImageCommand + " --quality 75 "
                + htmlUrl + " " + wkImageStorage + "/" + fileName + suffix;
        try {
            Runtime.getRuntime().exec(cmd);
            log.info("生成长图成功: " + cmd);
        } catch (IOException e) {
            log.error("生成长图失败: " + e.getMessage());
        }

        UploadTask task=new UploadTask(fileName,suffix);
        Future future=taskScheduler.scheduleAtFixedRate(task,500);
        task.setFuture(future);
    }

    class UploadTask implements Runnable{
        // 文件名称
        private String fileName;
        // 文件后缀
        private String suffix;
        //启动任务返回值，可用于停止计时器
        private Future future;
        //开始上传时间
        private long startTime;
        //上传次数
        private int uploadTimes=1;

        public void setFuture(Future future) {
            this.future = future;
        }

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime=System.currentTimeMillis();
        }

        @Override
        public void run() {
            if(System.currentTimeMillis()-this.startTime>30000){
                log.error("执行时间过长，终止任务"+fileName);
                future.cancel(true);
                return;
            }
            if(this.uploadTimes>5){
                log.error("上传次数过多，终止任务"+fileName);
                future.cancel(true);
                return;
            }
            String path=wkImageStorage+"/"+fileName+suffix;
            File file=new File(path);
            if(file.exists()){
                log.info(String.format("开始第%d次上传[%s]",this.uploadTimes,fileName));
                StringMap policy=new StringMap();
                policy.put("returnBody", CommunityUtil.getJSONString(0));
                Auth auth=Auth.create(accessKey,secretKey);
                String uploadToken=auth.uploadToken(shareBucketName,fileName,3600,policy);
                UploadManager manager=new UploadManager(new Configuration(Zone.zone2()));
                try{
                    //开始上传
                    Response response=manager.put(
                            path,fileName,uploadToken,null,"image/"+suffix,false
                    );
                    // 等待响应
                    JSONObject jsonObject=JSONObject.parseObject(response.bodyString());
                    if(jsonObject==null||jsonObject.get("code")==null||jsonObject.get("code").equals("0")){
                        log.info(String.format("第%d次上传失败[%s]",uploadTimes++,fileName));
                    }else {
                        log.info(String.format("第%d次上传成功[%s]",uploadTimes++,fileName));
                        this.future.cancel(true);
                    }
                }catch (QiniuException exception){
                    log.info(String.format("第%d次上传失败[%s]",uploadTimes++,fileName));
                }
            }else {
                log.info("等待图片生成["+fileName+"]");
            }

        }
    }

}
